#include "databasemanager.h"
#include <QCoreApplication>
#include <QThread>
#include <QTimer>
#include <QDebug>

DatabaseManager* DatabaseManager::instance()
{
    static QMutex instanceMutex;  // 单独的实例控制锁
    QMutexLocker lock(&instanceMutex);
    static DatabaseManager* instance = nullptr;

    if (!instance) {
        if (QThread::currentThread() != QCoreApplication::instance()->thread()) {
            qFatal("DatabaseManager must be created in main thread!");
        }
        instance = new DatabaseManager();
    }
    return instance;
}

DatabaseManager::DatabaseManager(QObject *parent) : QObject(parent)
{
    initializeConnections();  // 构造函数不再初始化mutex
}

DatabaseManager::~DatabaseManager()
{
    QMutexLocker lock(&globalMutex());  // 使用静态锁保护析构
    cleanupConnections();
}

void DatabaseManager::initializeConnections() {
    QMutexLocker lock(&globalMutex());  // 使用静态锁
    m_connections.clear();

    for (int i = 0; i < MAX_CONNECTIONS; ++i) {
        QTcpSocket* socket = new QTcpSocket(this);
        if (connectToServer(socket)) {
            m_connections.append(Connection(socket, false));
            qDebug() << "Connection" << i << "established";
        } else {
            socket->deleteLater();
            qWarning() << "Connection" << i << "failed";
        }
    }

    if (m_connections.isEmpty()) {
        qCritical("No database connections available!");
    }
}

QString DatabaseManager::sendRequest(const QString &query)
{
    QTcpSocket socket;
    socket.connectToHost("127.0.0.1", 12345);

    // 增加连接超时时间
    if (!socket.waitForConnected(3000)) {
        qWarning() << "Connection failed after 3 seconds";
        return "Error: Connection failed after 3 seconds";
    }

    // 发送请求
    QByteArray requestData = query.toUtf8() + '\n';
    qint64 bytesWritten = socket.write(requestData);

    if (bytesWritten != requestData.size()) {
        qWarning() << "Failed to write complete request";
        return "Error: Failed to write complete request";
    }

    // 确保数据发送完成
    if (!socket.waitForBytesWritten(3000)) {
        qWarning() << "Failed to write request data within 3 seconds";
        return "Error: Failed to write request data within 3 seconds";
    }

    // 接收响应
    QByteArray responseData;
    QElapsedTimer timer;
    timer.start();

    while (timer.elapsed() < 10000) { // 10秒总超时
        if (socket.waitForReadyRead(1000)) { // 每次等待1秒
            responseData += socket.readAll();

            // 检查是否收到完整响应(以换行符结束)
            if (responseData.contains('\n')) {
                QString response = QString::fromUtf8(responseData.trimmed());
                qDebug() << "Received response:" << response;
                return response;
            }
        }

        QCoreApplication::processEvents(); // 保持UI响应
    }

    qWarning() << "Timeout waiting for response after 10 seconds";
    return "Error: Timeout waiting for response after 10 seconds";
}

bool DatabaseManager::isConnected()
{
    QMutexLocker lock(&globalMutex());
    return !m_connections.isEmpty();
}

void DatabaseManager::cleanupConnections()
{
    QMutexLocker lock(&globalMutex());
    for (auto& conn : m_connections) {
        if (conn.socket) {
            conn.socket->close();
            conn.socket->deleteLater();
        }
    }
    m_connections.clear();
}

bool DatabaseManager::connectToServer(QTcpSocket* socket) {
    int retries = 3;
    while (retries-- > 0) {
        socket->connectToHost("127.0.0.1", 12345);
        if (socket->waitForConnected(3000)) {
            qDebug() << "Connected to server!";
            return true;
        }
        qWarning() << "Connection attempt failed, retries left:" << retries;
        QThread::msleep(1000);
    }
    return false;
}
